package com.sunwoda.springbootredis.service.impl;

import com.sunwoda.springbootredis.dao.UserDao;
import com.sunwoda.springbootredis.service.OpsKeyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @program: springbootredis
 * @description: 操作键
 * @author: SGR
 * @create: 2021-09-13 09:41
 **/
@Service
@Slf4j
public class OpsKeyServiceImpl implements OpsKeyService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
    * @Description:  删除键
    * @Param:
    * @return:
    * @Author: SGR
    * @Date: 2021-09-13
    */
    @Override
    public void deletekey() {

//        设置键序列化方案
        redisTemplate.setKeySerializer(new StringRedisSerializer());

//        绑定指定的键
        BoundValueOperations name = redisTemplate.boundValueOps("name");
        name.set("shiguorang");

        BoundValueOperations sex = redisTemplate.boundValueOps("sex");
        sex.set("男");
        log.info("修改前键名称："+sex.getKey());
//        修改键名称
        sex.rename("age");
        log.info("修改后键名称"+sex.getKey());


//        设置键过期时间
        name.expire(60, TimeUnit.SECONDS);
//        获取键的过期时间
        log.info("过期时间:"+name.getExpire());

//        获取键的数据类型
        DataType type = name.getType();
        log.info("键的数据类型:"+type);

//        判断是否存在键
        Boolean hasKey = redisTemplate.hasKey("name");
        if (hasKey){
//            删除键
            Boolean delete = redisTemplate.delete("name");
            log.info("删除键"+delete);
        }

        String o = (String) name.get();

        log.info(o);

    }
}
